<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="mb-4">
      <el-form-item label="角色筛选">
        <RoleSelect
          v-model="queryParams.roleId"
          :multiple="false"
          placeholder="请选择"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="状态筛选">
        <el-select 
          v-model="queryParams.status" 
          placeholder="请输入" 
          clearable 
          style="width: 200px"
        >
          <el-option 
            v-for="dict in sys_normal_disable" 
            :key="dict.value" 
            :label="dict.label" 
            :value="dict.value" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="搜索用户">
        <el-input 
          v-model="queryParams.searchValue" 
          placeholder="姓名或手机号" 
          clearable 
          style="width: 240px" 
          @keyup.enter="handleQuery" 
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleAdd">新增用户</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户数据表格 -->
    <el-table v-loading="loading" :data="userList" style="width: 100%">
      <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true" />
      <el-table-column label="手机号" align="center" prop="phonenumber">
        <template #default="scope">
          <span v-if="scope.row.phonenumber">{{ maskPhone(scope.row.phonenumber) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" prop="roles">
        <template #default="scope">
          <span v-if="scope.row.roles && scope.row.roles.length > 0">
            {{ scope.row.roles.map(r => r.roleName).join(', ') }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
            :disabled="scope.row.userId === 1"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录" align="center" prop="loginDate" width="160">
        <template #default="scope">
          <span v-if="scope.row.loginDate">
            {{ parseTime(scope.row.loginDate, '{y}-{m}-{d}') }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            @click="handleUpdate(scope.row)"
            v-if="scope.row.userId !== 1"
          >
            编辑
          </el-button>
          <el-button 
            link 
            type="primary" 
            @click="openPasswordDialog(scope.row)"
            v-if="scope.row.userId !== 1"
          >
            修改密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination 
      v-show="total > 0" 
      :total="total" 
      v-model:page="queryParams.pageNum" 
      v-model:limit="queryParams.pageSize" 
      @pagination="getList" 
    />

    <!-- 编辑用户对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码/用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <RoleSelect v-model="form.roleId" :multiple="false" placeholder="选择角色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId == undefined" label="初始密码" prop="password">
              <el-input 
                v-model="form.password" 
                placeholder="请输入" 
                type="password" 
                maxlength="20" 
                show-password 
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否启用">
              <el-switch v-model="form.status" active-value="0" inactive-value="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否默认客服">
              <el-switch v-model="form.wxShowFlag" active-value="1" inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="相关备注..."></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">保 存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="修改密码" v-model="passwordDialogOpen" width="420px" append-to-body>
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordRef" label-width="80px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" placeholder="请输入新密码" type="password" maxlength="20" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
          <el-button @click="cancelPasswordForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserSimple">
import { changeUserStatus, getUser } from "@/api/system/user"
import { resetPwd, listUser as listFangUser, addUser as addFangUser, updateUser as updateFangUser } from "@/api/fang/user"
import { parseTime } from "@/utils/ruoyi"
import RoleSelect from "@/components/RoleSelect/index.vue"

const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex")

const userList = ref([])
const open = ref(false)
const loading = ref(true)
const total = ref(0)
const title = ref("")
const postOptions = ref([])
const roleOptions = ref([])

// 重置密码对话框及表单
const passwordDialogOpen = ref(false)
const passwordRef = ref(null)
const passwordForm = reactive({ userId: undefined, password: undefined })
const passwordRules = {
  password: [
    { required: true, message: "用户密码不能为空", trigger: "blur" },
    { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
    { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\ |", trigger: "blur" }
  ]
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    roleId: undefined,
    searchValue: undefined
  },
  rules: {
    userName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }
    ],
    nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
      { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
    ],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phonenumber: [
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)


/** 手机号脱敏 */
function maskPhone(phone) {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

/** 查询用户列表 */
function getList() {
  loading.value = true
  
  // 处理搜索关键词：可能是姓名或手机号
  const params = { ...queryParams.value }
  // if (params.searchValue) {
  //   // 如果搜索关键词是手机号格式，则设置为phonenumber，否则设置为userName
  //   if (/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(params.searchValue)) {
  //     params.phonenumber = params.searchValue
  //     params.userName = undefined
  //   } else {
  //     params.userName = params.searchValue
  //     params.phonenumber = undefined
  //   }
  //   params.searchValue = undefined
  // }
  
  listFangUser(params).then(res => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10
  handleQuery()
}

/** 用户状态修改（Switch 交互，需二次确认） */
function handleStatusChange(row) {
  const text = row.status === "0" ? "启用" : "禁用"
  const current = row.status
  proxy.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function () {
    return changeUserStatus(row.userId, current)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    // 撤销 Switch 变更
    row.status = current === "0" ? "1" : "0"
  })
}

/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    nickName: undefined,
    userName: undefined,
    password: undefined,
    status: "0",
    wxShowFlag: "0",
    remark: undefined,
    roleId: undefined
  }
  proxy.resetForm("userRef")
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 打开修改密码弹窗 */
function openPasswordDialog(row) {
  passwordForm.userId = row.userId
  passwordForm.password = undefined
  passwordDialogOpen.value = true
}

/** 提交修改密码 */
function submitPasswordForm() {
  proxy.$refs["passwordRef"].validate(valid => {
    if (!valid) return
    resetPwd(passwordForm.userId, passwordForm.password).then(() => {
      proxy.$modal.msgSuccess("密码修改成功")
      passwordDialogOpen.value = false
      passwordForm.userId = undefined
      passwordForm.password = undefined
    })
  })
}

/** 取消修改密码 */
function cancelPasswordForm() {
  passwordDialogOpen.value = false
  passwordForm.userId = undefined
  passwordForm.password = undefined
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加用户"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const userId = row.userId
  getUser(userId).then(response => {
    form.value = response.data
    // 兼容后端返回，回填 roleId 与 userName
    if (Array.isArray(response.roleIds) && response.roleIds.length > 0) {
      form.value.roleId = response.roleIds[0]
    }
    form.value.userName = response.data.userName || response.data.phonenumber
    open.value = true
    title.value = "修改用户"
    form.value.password = ""
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.userId != undefined) {
        const payload = { ...form.value }
        delete payload.password
        updateFangUser(payload).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        const payload = { ...form.value }
        addFangUser(payload).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>

